import redis
from datetime import datetime, timedelta, time
from setting import config

__all__ = [
    "redispy"
]


class Redispy:
    def __init__(self):
        self._connect = redis.Redis.from_url(config.REDIS_URL, decode_responses=True)


    def set_token(self, name: str, token: str):
        """
        设置token
        """
        key = f"token:{name}:{token}"
        value = datetime.now().timestamp()
        return self._connect.set(key, value, ex=config.ACCESS_TOKEN_EXPIRE_MINUTES*60)


    def get_token(self, name: str, token: str):
        """
        获取token
        """
        key = f"token:{name}:{token}"
        return self._connect.get(key).decode('utf-8')
    
    
    def delete_token(self, name: str, token: str):
        """
        删除token
        """
        key = f"token:{name}:{token}"
        return self._connect.delete(key)
    
    
    def clean_token(self, name: str):
        """
        清理token
        """
        key = f"token:{name}:*"
        for i in self._connect.scan_iter(key):
            self._connect.delete(i)
            
        return True


    def is_token_exists(self, name: str, token: str):
        """
        判断token是否存在
        """
        key = f"token:{name}:{token}"
        return self._connect.exists(key)


    def set_login_success(self, name: str):
        """
        记录登录成功
        """
        key = f"login:{name}"
        if self._connect.exists(key):
            self._connect.delete(key)
            
        return True
    
    
    def set_login_failed(self, name: str):
        """
        记录登录失败
        """
        key = f"login:{name}"
        if self._connect.exists(key):
            self._connect.incr(key)
        else:
            self._connect.set(key, 1, ex=30*60)
            
        return True



    def is_login_allow(self, name: str):
        """
        是否允许登录
        """
        key = f"login:{name}"
        value = self._connect.get(key)
        if self._connect.exists(key) and int(value) > 5:
            # 30分钟内，只能有5次登录失败
            return False
        return True




    def __del__(self):
        self._connect.close()


redispy = Redispy()
